package org.meb.conquest.web.services;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;
import javax.inject.Inject;

import org.apache.commons.lang.StringUtils;
import org.meb.conquest.db.model.loc.Card;

@FacesConverter(value = "card", forClass = Card.class)
public class CardConverter implements Converter {

	@Inject
	private SearchService searchService;

	public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
		if (StringUtils.isBlank(value)) {
			return null;
		} else {
			try {
				Long id = Long.valueOf(value);
				return searchService.findUnique(new Card(id));
			} catch (NumberFormatException exception) {
				throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error",
						"Not a valid card"));
			}
		}
	}

	public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
		if (value == null || value.equals("")) {
			return "";
		} else {
			return String.valueOf(((Card) value).getId());
		}
	}
}